#!/usr/bin/env python
# -*- coding: UTF-8 -*-

from cors_middleware import CorsResource
import json

class ItemResource(CorsResource):
    isLeaf = True

    def __init__(self, game_state):
        super().__init__()
        self.game_state = game_state

    def render_GET(self, request):
        # 物品相关逻辑
        self._set_cors_headers(request)

        # 获取玩家ID
        user_id = request.args.get(b'user_id', [b''])[0].decode()

        # 确保玩家存在
        if user_id:
            if user_id not in self.game_state.users:
                # 尝试从数据库加载
                user_data = self.game_state.load_user_from_db(user_id)
                if not user_data:
                    # 数据库中也不存在，创建新玩家
                    self.game_state.users[user_id] = {'x': 0, 'y': 0, 'inventory': []}
            else:
                # 玩家在内存中存在，确保数据库中也有
                self.game_state.save_user_to_db(user_id)

            # 返回玩家物品列表
            inventory = self.game_state.users[user_id].get('inventory', [])
            response = {
                'code': 0,
                'data': {
                    'items': inventory
                }
            }
        else:
            # 返回默认物品列表
            response = {
                'code': 0,
                'data': {
                    'items': ['sword', 'shield', 'potion']
                }
            }

        request.setHeader(b'Content-Type', b'application/json')
        return json.dumps(response).encode()

    def render_POST(self, request):
        """处理POST请求，示例：添加新物品"""
        self._set_cors_headers(request)
        # 获取POST数据
        content = request.content.read()
        try:
            data = json.loads(content.decode())

            # 解析物品信息
            item_name = data.get('name')
            item_type = data.get('type')
            user_id = data.get('user_id')

            # 验证必要参数
            if not item_name or not user_id:
                response = {
                    'code': 100,
                    'msg': 'Missing required fields: name and user_id'
                }
                request.setResponseCode(400)
            else:
                # 确保玩家存在
                if user_id not in self.game_state.users:
                    # 尝试从数据库加载
                    user_data = self.game_state.load_user_from_db(user_id)
                    if not user_data:
                        # 数据库中也不存在，创建新玩家
                        self.game_state.users[user_id] = {'x': 0, 'y': 0, 'inventory': []}
                elif 'inventory' not in self.game_state.users[user_id]:
                    self.game_state.users[user_id]['inventory'] = []

                # 将物品添加到玩家库存
                new_item = {
                    'name': item_name,
                    'type': item_type,
                    'id': len(self.game_state.users[user_id]['inventory']) + 1
                }
                self.game_state.users[user_id]['inventory'].append(new_item)

                # 保存到数据库
                self.game_state.save_user_to_db(user_id)

                response = {
                    'code': 0,
                    'msg': f'Item {item_name} added to user {user_id}',
                    'data': {
                        'item': new_item
                    }
                }
                request.setResponseCode(201)

        except json.JSONDecodeError:
            response = {
                'code': 100,
                'msg': 'Invalid JSON data'
            }
            request.setResponseCode(400)
        except Exception as e:
            response = {
                'code': 100,
                'msg': str(e)
            }
            request.setResponseCode(500)

        request.setHeader(b'Content-Type', b'application/json')
        return json.dumps(response).encode()
